package io.example.web;

import io.example.handler.AuthorHandler;
import io.example.handler.BookHandler;
import io.example.service.AuthorAsyncService;
import io.example.service.BookAsyncService;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.serviceproxy.ServiceProxyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Description: RestVerticle.java .<br>
 * <p>Created Time: 2020/10/22 16:31 </p>
 *
 * @author <a href="mail to: mengxiangyuancc@gmail.com" rel="nofollow">孟祥元</a>
 */
@Component
public class RestVerticle extends AbstractVerticle {
    private static final Logger logger = LoggerFactory.getLogger(RestVerticle.class);

    private BookAsyncService bookAsyncService;

    private AuthorAsyncService authorAsyncService;

    @Override
    public void start(Promise<Void> startFuture) throws Exception {
        ServiceProxyBuilder serviceProxyBuilder = new ServiceProxyBuilder(vertx);
        // 获取代理服务: BookAsyncServiceVertxEBProxy
        bookAsyncService = serviceProxyBuilder.setAddress(BookAsyncService.ADDRESS)
            .build(BookAsyncService.class);
        // 获取代理服务: AuthorAsyncServiceVertxEBProxy
        authorAsyncService = serviceProxyBuilder.setAddress(AuthorAsyncService.ADDRESS)
            .build(AuthorAsyncService.class);
        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());
        router.post("/book").handler(routingContext -> BookHandler.addBook(routingContext, bookAsyncService));
        router.get("/books").handler(routingContext -> BookHandler.getAllBooks(routingContext, bookAsyncService));
        router.post("/author").handler(routingContext -> AuthorHandler.addAuthor(routingContext, authorAsyncService));
        router.get("/authors").handler(routingContext -> AuthorHandler.getAllAuthors(routingContext,
            authorAsyncService));

        vertx.createHttpServer().requestHandler(router).listen(8081, listen -> {
            if (listen.succeeded()) {
                logger.info("[Vertx] Http Server started on port(s): 8081 (http)");
                startFuture.complete();
            } else {
                startFuture.fail(listen.cause());
            }
        });
    }

}
